<template>
  <el-card>
    <PlusSearch
        v-model="searchParam"
        :columns="tableConfig"
        :show-number="4"
        @search="handleSearch"
    />
  </el-card>
  <div><br/></div>
  <el-button
      type="primary"
      @click="showUpload = true"
      class="mb-4"
  >
    <!-- 用 el-icon 包裹图标组件，组件名是 ElIconDownload（驼峰命名） -->
    <el-icon>
      <el-icon-upload/>
    </el-icon>
    导入
  </el-button>
  <el-card class="table-container">
    <div>
      <PlusTable ref="plusPageRef" :columns="tableConfig" :table-data="tableData"
                 :rowKey="'id'"
                 :is-selection="false"
                 :header-cell-style="{ background: '#f5f7fa' }"
                 :pagination="pagination"
                 @paginationChange="handlePaginationChange"
      >
        <template v-slot:title>

          <el-dialog v-model="showUpload" title="选择 " width="400">
            <el-upload
                ref="uploadRef"
                class="upload-demo"
                v-model:file-list="fileList"
                drag
                :action="uploadUrl"
                :on-error="handleError"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
                :multiple=false
                accept=".xlsx"
                :auto-upload="true"
                :limit="1"
                :headers="uploadHeaders"
            >
              <el-icon class="el-icon--upload">
                <UploadFilled/>
              </el-icon>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip">只能上传xlsx文件<br/>
                  如果还没有模板, 请点击下载:
                  <el-link @click="handleTemplateDownload">下载模板</el-link>
                </div>
              </template>
            </el-upload>
          </el-dialog>
        </template>
      </PlusTable>
    </div>
  </el-card>


</template>
<script setup lang="ts">
import {
  type PageInfo,
  type PlusColumn, PlusPage, type PlusPaginationProps,
  PlusSearch,
  PlusTable,
  useTable
} from "plus-pro-components";
import {computed, onMounted, type Ref, ref,} from "vue";
import {
  ElButton,
  ElMessage, ElUpload,
  type UploadFile,
  type UploadFiles,
  type UploadInstance,
  type UploadUserFile
} from "element-plus";
import {getStores} from "../api/store.ts";
import {UploadFilled} from "@element-plus/icons-vue";
import {useAuthStore} from "../stores/auth.ts";
import type {Store, StoreSearchParam} from "../model/store.ts";
import axios from '../utils/request';
import {useBrandsStore} from "../stores/brand.ts";
import {useSalesRepsStore} from "../stores/sales_rep.ts";
import {addCascadeOptions} from "../model/common.ts";

const uploadRef = ref<UploadInstance>({} as UploadInstance);
const showUpload = ref(false);
const uploadUrl = ref('/api/stores/upload'); // 替换为你的本地接口地址ref('/api/stores/store_template');
// 替换为你的本地接口地址
const fileList = ref<UploadUserFile[]>([])
const handleTemplateDownload = async () => {
  try {
    // 发起请求：注意设置 responseType 为 'blob'（关键！）
    const response = await axios.get('/stores/template', {
      responseType: 'blob', // 告诉 axios 响应数据是二进制流
      headers: {
        // 携带 Token（若后端需要认证）
        Authorization: `Bearer ${authStore.token}`
      }
    });

    // 解析 blob 数据，触发浏览器下载
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // xlsx 文件 MIME 类型
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'store_template.xlsx'; // 下载的文件名
    document.body.appendChild(a);
    a.click();

    // 释放资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  } catch (error) {
    console.error('模板下载失败：', error);
    ElMessage.error('模板下载失败，请联系管理员');
  }
}
const beforeUpload = (file: File) => {
  const isXlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.name.endsWith('.xlsx');
  if (!isXlsx) {
    ElMessage.error('只能上传xlsx文件');
    return false;
  }
  return true;
};
const handleSuccess = (response: any, file: UploadFile, files: UploadFiles) => {
  console.log(file, files);
  if (response) {
    ElMessage.success('文件上传成功');
    showUpload.value = false;
    uploadRef.value.clearFiles()
  } else {
    ElMessage.error('文件上传失败');
  }
};

const handleError = (err: any, file: UploadFile, files: UploadFiles) => {
  console.log(file, files);
  ElMessage.error(`文件上传失败: ${err.message}`);
};
let authStore = useAuthStore();
const uploadHeaders = computed(() => ({
  // 如果 Token 存在，添加 Authorization 头；不存在则不添加（避免无效请求头）
  ...(authStore.token ? {Authorization: `Bearer ${authStore.token}`} : {})
}));

const changingPharmacy: Ref<Store> = ref({})
const defaultValues = {
  sales_rep: ['刘敏娇']
} as StoreSearchParam

const brandOptions = ref([]);
const srOptions = ref([]);
const brandSelectOptions = computed(() => brandOptions.value);
const srSelectOptions = computed(() => srOptions.value);
const searchParam: Store = ref({...defaultValues})
const tableConfig: PlusColumn[] = [
  {
    label: '品牌',
    width: 80,
    prop: 'brand',
    valueType: 'select',
    options: brandSelectOptions,
    fieldProps: {
      multiple: true,
    }
  },
  {
    label: '业务代表',
    width: 90,
    prop: 'sales_rep',
    valueType: 'select',
    options: srSelectOptions,
    fieldProps: {
      multiple: true,
    }
  },
  {
    label: '门店名称',
    width: 360,
    prop: 'name',
    hideInSearch: true,
  },
  {
    label: '区县',
    width: 100,
    prop: 'region',
    valueType: 'cascader',
    fieldProps: {
      props: {multiple: true},
      showAllLevels: false,
    },
    hideInTable: true, //表格中不展示, 仅用作查询
    options: () => {
      return new Promise(resolve => {
        resolve(addCascadeOptions)
      })
    }
  },
  {
    label: '区县',
    width: 100,
    prop: 'district',
    hideInSearch: true,
  },
  {
    label: 'ID',
    width: 0,
    prop: 'id',
    hideInSearch: true,
    hideInTable: true,
    hideInForm: true,
  },
  {
    label: '市',
    width: 80,
    prop: 'city',
    hideInSearch: true
  },
  {
    label: '省',
    width: 80,
    prop: 'province',
    hideInSearch: true
  },
  {
    label: '地址',
    width: 620,
    prop: 'address',
    hideInSearch: true,
  },
  {
    label: '店长',
    width: 200,
    prop: 'manager',
    hideInSearch: true
  },
  {
    label: '电话',
    width: 150,
    prop: 'phone',
    hideInSearch: true
  }
]

// 2. 在 onMounted 中初始化 Pinia 并读取状态（此时组件已挂载，Pinia 就绪）
onMounted(() => {
      const authStore = useAuthStore()
      const brandsStore = useBrandsStore()
      const salesRepsStore = useSalesRepsStore()
      salesRepsStore.sales_reps.forEach(item => {
        srOptions.value.push({
          label: item,
          value: item
        });
      })
      brandsStore.brands.forEach(item => {
        brandOptions.value.push({
          label: item.name,
          value: item.id
        });
      })
      // 读取 userInfo（此时状态已加载）
      const currentName = authStore.userInfo?.name;
      searchParam.value.sales_rep = (currentName && authStore.userInfo.role === 'sales_rep')
          ? [currentName]
          : []
      const defaultRegion = addCascadeOptions[0]
      searchParam.value.region = defaultRegion.children.map((item) => [defaultRegion.value, item.value])
    }
);
const totalTableData = ref<Store[]>([]);
const {tableData, total, pageInfo, buttons} = useTable<Store[]>()


const defaultPageInfo = ref({
  page: 1,
  pageSize: 10,
})
const pagination: false | Partial<PlusPaginationProps> = ref({
  total,
  modelValue: defaultPageInfo.value,
  pageSizeList: [10, 20, 50],
  align: 'right'
})

const handleSearch = async (query: Partial<PageInfo> & StoreSearchParam) => {
  let resData = await getStores({
    ...query,
    ...defaultPageInfo.value
  })
  totalTableData.value = resData
  console.log('total', total)
  total.value = resData.length
  let _pageInfo = pageInfo.value
  console.log(_pageInfo)
  let page = _pageInfo.page
  let pageSize = _pageInfo.pageSize
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  tableData.value = resData.slice(startIndex, endIndex);
  console.log('tableData', tableData, 'startIndex', startIndex, 'endIndex', endIndex);
  return {data: totalTableData, total: total, success: true}
}

const handlePaginationChange = (_pageInfo: PageInfo): void => {
  console.log(_pageInfo)
  pageInfo.value = _pageInfo
  const {page, pageSize} = _pageInfo;
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  tableData.value = totalTableData.value.slice(startIndex, endIndex);
}


const show = ref<boolean[]>([])

buttons.value = [
  {
    text: '取消编辑',
    code: 'cancel',
    props: {
      type: 'warning'
    },
    show: row => !!show.value[row.id]
  },
  {
    // 保存
    text: '保存',
    code: 'save',
    props: {
      type: 'primary'
    },
    show: row => !!show.value[row.id]
  },
  {
    text: '编辑',
    code: 'edit',
    props: {
      type: 'primary'
    },
    show: row => !show.value[row.id]
  },
  {
    text: '删除',
    code: 'delete',
    props: {
      type: 'danger'
    },
    confirm: {},
    show: row => !show.value[row.id]
  }
]
</script>

<style scoped>
/* 表格容器样式 */
.table-container {
  position: relative; /* 固定定位，使表格保持在视口底部 */
  top: 15px;
  bottom: 0; /* 距离底部 0px */
  left: 0; /* 距离左侧 0px */
  right: 0; /* 距离右侧 0px */
  max-height: 800px; /* 表格容器固定高度（根据需求调整） */
  overflow: auto; /* 超出部分显示滚动条（上下左右都支持） */
  background: #fff; /* 背景色，避免透明导致遮挡内容 */
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1); /* 底部阴影，提升视觉效果 */
  z-index: 1000; /* 确保表格在其他内容之上（根据项目层级调整） */
}

/* 解决 Element Plus 表格头部与内容对齐问题 */
/*.el-table__header-wrapper,
.el-table__body-wrapper {
  width: 100%;
}*/

/* 优化滚动条样式（可选） */
.table-container::-webkit-scrollbar {
  width: 4px; /* 垂直滚动条宽度 */
  height: 8px; /* 水平滚动条高度 */
}

.table-container::-webkit-scrollbar-thumb {
  background: #ccc; /* 滚动条滑块颜色 */
  border-radius: 4px; /* 滚动条滑块圆角 */
}

.table-container::-webkit-scrollbar-thumb:hover {
  background: #999; /* 滚动条滑块 hover 颜色 */
}
</style>